import java.util.*;
import java.io.*;

public class Example {
    private static final int BUFFER_SIZE = 8192;

    public static void main(String[] args) {
        System.out.println("这个程序输出文件的二进制表示形式，将其保存在一个新的文本文件中。\n" +
                "请注意，将文件转为二进制表示形式后容量可能显著增大，请不要对较大的文件进行此操作。\n" +
                "请在下方输入文件名：");
        System.out.print(">");
        Scanner cin = new Scanner(System.in);
        String path = cin.nextLine();
        File file = new File(path);
        if (!file.exists() || !file.isFile()) {
            System.out.print("文件不存在，请检查您的输入，然后重试。");
            return;
        }
        //生成新文件的路径
        String filePath;
        String fileName;
        String newFilePath;
        StringBuilder newFileName;
        try {
            newFileName = new StringBuilder(file.getName());
            int dotIndex = file.getName().lastIndexOf('.');
            newFileName.delete(dotIndex, newFileName.length());
            newFileName.append(" - Binary.txt");
            filePath = file.getCanonicalPath();
            fileName = file.getName();
            newFilePath = filePath.substring(0, filePath.length() - fileName.length()) + newFileName;
        }
        catch (IOException ex) {
            System.out.println("在生成新文件的路径时遭遇异常，程序被迫中止。");
            return;
        }
        File newFile = new File(newFilePath);
        if (newFile.exists()) {
            System.out.println("警告：同级目录下已存在名为 " + newFileName + " 的文件，请在将其移出后重试。");
            return;
        }
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
             PrintWriter out = new PrintWriter(new BufferedOutputStream(
                     new FileOutputStream(newFilePath), BUFFER_SIZE));) {
            while (true) {
                int b = in.read();
                if (b < 0) break;
                long bin = dec2Bi(b);
                String bin_str = String.valueOf(bin);
                bin_str = complete(bin_str);
                out.print(bin_str);
            }
        }
        catch (IOException ex) {
            System.out.println("在将文件转为二进制形式的过程中遭遇错误，程序被迫中止。");
            return;
        }
        System.out.println("完成");
    }

    //将长度小于8的字符串左侧补0
    private static String complete(String str) {
        StringBuilder builder = new StringBuilder(str);
        while (builder.length() < 8) builder.insert(0, "0");
        return builder.toString();
    }

    private static long dec2Bi(int x) {
        int remainder = x;
        long ret = 0;
        int level = 0;
        while (remainder != 0) {
            ret += (long) remainder % 2 * Math.pow(10, level++);
            remainder /= 2;
        }
        return ret;
    }
}